package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result.Result;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<DishDto>> dishPage(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<Dish>()
                .like(name != null, Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, queryWrapper);
        BeanUtil.copyProperties(dishPage, dishDtoPage, "records");

        List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().eq(Category::getType, 1));
        Map<Long, String> map = categoryList.stream()
                .collect(Collectors.toMap(Category::getId, Category::getName));

        List<Dish> dishRecords = dishPage.getRecords();
        List<DishDto> records = dishRecords.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(dish, dishDto);
            String categoryName = map.get(dish.getCategoryId());
            if (categoryName != null && !categoryName.isEmpty()) {
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;

        }).collect(Collectors.toList());
        dishDtoPage.setRecords(records);
        return Result.success(dishDtoPage);
    }

    /**
     * 根据id回显菜品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdDishWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     * 添加菜品和对应的口味
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> saveDish(@RequestBody DishDto dishDto) {
        log.info("本次添加的菜品信息:{}", dishDto.toString());
        dishService.saveDishWithFlavor(dishDto);

        return Result.success();
    }

    /**
     * 批量删除菜品，如果关联口味则一并删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> deleteDish(@RequestParam List<Long> ids) {
        log.info("当前接收到的参数ids为{}", ids);
        dishService.batchDeleteDish(ids);

        return Result.success();
    }

    /**
     * 修改菜品及口味
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> updateDish(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);
        return Result.success();
    }

    /**
     * 批量修改菜品状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> batchUpdateDishStatus(@PathVariable String status, @RequestParam List<Long> ids) {
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId, ids)
                .set(Dish::getStatus, status);
        dishService.update(updateWrapper);
        return Result.success();
    }

    /**
     * 根据分类id获取菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List<Dish>> listDishByCategoryId(Long categoryId) {
        return Result.success(dishService.list(new LambdaQueryWrapper<Dish>()
                .eq(categoryId != null, Dish::getCategoryId, categoryId)));
    }


}
